package com.atguigu.JVMDay02;

import java.lang.ref.SoftReference;
import java.util.concurrent.TimeUnit;

//软引用
public class SoftReferenceTest {
    public static void main(String[] args) {
        //软引用就是内存空间足够的时候不回收，内存不足时回收
        //创建对象，建立软引用
        SoftReference<Person> softReference = new SoftReference<>(new Person(25,"waiwaiqiucha"));
        //从软引用中获得强引用对象
        System.out.println(softReference.get());
        try {
            byte[] bytes = new byte[7*1024*1024];//7Mb
        }catch (Throwable e){
            e.printStackTrace();
        }finally{
            System.out.println("finally");
            //再次从软引用中获取数据，在报OOM之前，垃圾回收器会回收软引用的可达对象
            System.out.println(softReference.get());//设置堆内存变小后，软引用将会被回收
        }
  //      System.out.println("finally");
//        System.gc();
        //线程睡眠几秒
//        try {
//            TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
 //       System.out.println(softReference.get());

    }
}
class Person{
    Integer age;
    String name;

    public  Person(Integer age,String name){
        this.age=age;
        this.name=name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}